#pragma once

#include <iostream>
#include <cstdio>
#include <string>

#include "Init.hpp"

using namespace std;

Init init;

class Task
{
public:
    Task(int sockfd, const string &clientip, const uint16_t clientport)
        : _sockfd(sockfd),
          _ip(clientip),
          _port(clientport)
    {
    }

    void run()
    {
        // 接收和发送
        char inbuffer[1024] = {0};
        ssize_t s = read(_sockfd, inbuffer, sizeof(inbuffer));
        if (s > 0) // 读到了数据
        {
            inbuffer[s] = 0;
            cout << inbuffer << endl;
            string mess = init.Translation(inbuffer);


            int n = write(_sockfd, mess.c_str(), mess.size());
            if(n < 0)
            {
                lg(Warning, "write error, errno : %d, errstring: %s", errno, strerror(errno));
            }
        }
        else if (s == 0) // 客户端退出
        {
            lg(Info, "[%s:%d] quit, server close sockfd: %d", _ip.c_str(), _port, _sockfd);
        }
        else // read出错
        {
            lg(Warning, "read error, sockfd: %d, client ip: %s, client port: %d", _sockfd, _ip.c_str(), _port);
        }
        close(_sockfd);
    }

    ~Task()
    {
    }

private:
    int _sockfd;
    string _ip;
    uint16_t _port;
};